package org.lds.logger.config.appender;

import org.apache.commons.io.FileUtils;
import org.lds.logger.config.filter.AbstractAppenderFilter;
import org.lds.logger.config.layout.Layout;
import org.lds.logger.exception.LoggerException;
import org.lds.logger.util.Utils;

import java.io.File;
import java.io.OutputStream;

public class FileAppender extends AbstractAppender {
    private OutputStream outputStream;

    public FileAppender() {
    }

    public FileAppender(String name, String destination, int priority, AbstractAppenderFilter abstractAppenderFilter, Layout layout) {
        super(name, destination, priority, abstractAppenderFilter, layout);
    }

    @Override
    public void initialize() {
        openFile();
    }

    public void openFile() {
        if (outputStream != null) return;
        try {
            outputStream = FileUtils.openOutputStream(new File(getDestination()), true);
        } catch (Throwable e) {
            throw new LoggerException("FileAppender outputStream open fail. error=" + e.getMessage());
        }
    }

    public void closeFile() {
        if (outputStream != null) {
            try {
                outputStream.close();
                outputStream = null;
            } catch (Throwable e) {
                throw new LoggerException("outputStream close fail. error=" + e.getMessage());
            }
        }
    }

    @Override
    protected void doAppend(String message) {
        if (outputStream == null) return;
        try {
            outputStream.write(message.getBytes(getLayout().getCharset()));
        } catch (Throwable e) {
            Utils.report("outputStream write fail. error=" + e.getMessage());
        }
    }

}
